<template>
  <div class="goods" v-title data-title="我的商品">
    <div class="top-header"></div>
    <div class="security_content">
      <div class="security">
        <span class="security-title"></span>
        <el-tabs
          tab-position="left"
          v-model="active"
          @tab-click="handleClick"
          style="min-height: 500px"
        >
          <el-tab-pane label="图书添加" name="0">
            <addGood />
          </el-tab-pane>
          <el-tab-pane label="我的商品" name="1">
            <mesGoods
              style="
                width: 90%;
                margin-bottom: 30px;
              "
              :userId="this.addGoods.userId"
            />
          </el-tab-pane>
          <el-tab-pane label="所有订单" name="2">
            <sellOrder :userId="this.addGoods.userId" />
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </div>
</template>

<script>
import sellOrder from "../../components/MyGoodPage/SellOrder.vue";
import mesGoods from "../../components/MyGoodPage/MesGoods.vue";
import addGood from "../../components/MyGoodPage/AddGood.vue";
import api from "../../api";
import { mapState } from "vuex";
export default {
  components: {
    sellOrder,
    mesGoods,
    addGood,
  },
  data() {
    var validateCategory = (rule, value, callback) => {
      if (value === "") {
        callback("请选择您的商品类别!");
      } else {
        callback();
      }
    };
    var validateName = (rule, value, callback) => {
      if (value === "") {
        callback("请填写您的商品名字!");
      } else {
        callback();
      }
    };
    var validatePrice = (rule, value, callback) => {
      if (value === "") {
        callback("请填写您的商品价格!");
      } else {
        callback();
      }
    };
    var validateStore = (rule, value, callback) => {
      if (value === "") {
        callback("请填写您的商品数量!");
      } else {
        callback();
      }
    };
    var validateAppearance = (rule, value, callback) => {
      if (value === "") {
        callback("请选择您的商品品相!");
      } else {
        callback();
      }
    };
    var validateImage = (rule, value, callback) => {
      if (value === "") {
        callback("请上传您的商品封面!");
      } else {
        callback();
      }
    };
    var validateDescribe = (rule, value, callback) => {
      if (value === "") {
        callback("请输入您的商品描述!");
      } else {
        callback();
      }
    };
    return {
      addGoods: {
        userId: "", //用户编号
        name: "", //书名
        image: "", //商品图片URL
        price: "", //价格（一个浮点数）,
        appearance: "", //品相
        ISBN: "", //ISBN码
        category: "", //种类名
        author: "", //作者
        translator: "", //译者
        version: "", //版本号
        store: "", //库存,一个整数（当前阶段没有用）
        freight: "0", //邮费，一个浮点数
        pressHorse: "", //出版社名
        publicationDate: "", //出版日期
        updateDate: "", //更新时间
        describe: "", //描述
      },
      hideUpload: false,
      filesNum: 0,
      upDataVisable: false,
      productTree: [{}],
      appOptions: [
        {
          value: "五成新",
          label: "五成新",
        },
        {
          value: "六成新",
          label: "六成新",
        },
        {
          value: "七成新",
          label: "七成新",
        },
        {
          value: "七五新",
          label: "七五新",
        },
        {
          value: "八成新",
          label: "八成新",
        },
        {
          value: "八五新",
          label: "八五新",
        },
        {
          value: "九成新",
          label: "九成新",
        },
        {
          value: "九五新",
          label: "九五新",
        },
        {
          value: "九九新",
          label: "九九新",
        },
        {
          value: "全新",
          label: "全新",
        },
      ],
      active: "0",
      rules: {
        category: [
          {
            validator: validateCategory,
            trigger: "blur",
          },
        ],
        name: [
          {
            validator: validateName,
            trigger: "blur",
          },
        ],
        price: [
          {
            validator: validatePrice,
            trigger: "blur",
          },
        ],
        store: [
          {
            validator: validateStore,
            trigger: "blur",
          },
        ],
        appearance: [
          {
            validator: validateAppearance,
            trigger: "blur",
          },
        ],
        image: [
          {
            validator: validateImage,
            trigger: "blur",
          },
        ],
        describe: [
          {
            validator: validateDescribe,
            trigger: "blur",
          },
        ],
      },
    };
  },
  computed: {
    ...mapState("login", ["user"]),
  },
  methods: {
    priceInput(val) {
      let codeReg = new RegExp("[0-9]+"), //正则 数字；
        len = val.length,
        str = "";
      for (var i = 0; i < len; i++) {
        if (codeReg.test(val[i])) {
          str += val[i];
        }
      }
      this.addGoods.price = str;
    },
    storeInput(val) {
      let codeReg = new RegExp("[0-9]+"), //正则 数字；
        len = val.length,
        str = "";
      for (var i = 0; i < len; i++) {
        if (codeReg.test(val[i])) {
          str += val[i];
        }
      }
      this.addGoods.store = str;
    },
    handleUpdataClose(done) {
      this.$confirm("确认关闭？您的操作将不会保存!")
        .then((_) => {
          done();
          this.addGoods.image = "";
          this.$refs["upload"].clearFiles();
        })
        .catch((_) => {});
    },
    uploadFile(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
        this.$refs["upload"].clearFiles();
        return;
      }
      this.imgTemp = file.raw;
      this.filesNum++;
      if (this.filesNum == 1) {
        this.hideUpload = true;
      }
    },
    remove() {
      this.filesNum--;
      if (this.filesNum < 1) {
        this.hideUpload = false;
      }
    },
    cancel() {
      this.$refs["addGoods"].resetFields();
      if (this.addGoods.image != "") {
        this.$refs["upload"].clearFiles();
      }
    },
    determine(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let param = new URLSearchParams();
          var formdata = new FormData();
          console.log(this.addGoods);
          formdata.append("userId", this.addGoods.userId);
          formdata.append("name", this.addGoods.name);
          formdata.append("image", this.addGoods.image);
          formdata.append("price", this.addGoods.price);
          formdata.append("appearance", this.addGoods.appearance);
          formdata.append("ISBN", this.addGoods.ISBN);
          formdata.append(
            "categoryId",
            this.addGoods.category[this.addGoods.category.length - 1]
          );
          formdata.append("author", this.addGoods.author);
          formdata.append("translator", this.addGoods.translator);
          formdata.append("version", this.addGoods.version);
          formdata.append("store", this.addGoods.store);
          formdata.append("freight", this.addGoods.freight);
          formdata.append("pressHorse", this.addGoods.pressHorse);
          formdata.append("publicationDate", this.addGoods.publicationDate);
          formdata.append("describe", this.addGoods.describe);
          formdata.append("status", "0");
          api.addGood(formdata).then((res) => {
            // console.log(res.data);
            this.$message({
              message: "商品创建成功，请前往我的商品查看!",
              type: "success",
            });
            this.cancel();
          });
        } else {
          return;
        }
      });
    },
    handleClick(tab) {
      this.$router.push({
        path: "/mygoods",
        query: {
          active: this.active,
        },
      });
    },
  },
  created() {
    this.addGoods.userId = this.user.userId;
    api.getAllCategories().then((res) => {
      this.productTree = JSON.parse(
        JSON.stringify(res.data)
          .replace(/id/g, "value")
          .replace(/name/g, "label")
          .replace(/subList/g, "children")
      );
    });
    if (this.$route.query.active != "") {
      this.active = this.$route.query.active;
    }
  },
};
</script>

<style lang="less" scoped>
.goods {
  border-radius: 4px;
  padding-bottom: 20px;
  width: 100%;
  min-height: 100%;
  overflow: auto;
  text-align: left;
  padding-left: 5%;
  padding-right: 5%;
  // border: 1px solid #ddd;
  background-color: snow;
  // .top-header {
  //   width: 100%;
  //   height: 100px;
  //   background: url("http://8.130.171.48:8080/img/BG.jpg");
  //   z-index: 10;
  // }
  .security_content {
    overflow: hidden;
    width: 100%;
    height: 100%;
    margin: 10px auto 0px;
    // box-shadow: 0 2px 4px rgb(0 0 0 / 14%);
    background: #fafafa;
    border-radius: 4px;
    .security {
      float: left;
      width: 100%;
      height: 100%;
      overflow: hidden;
      .security-title {
        display: block;
        width: 100%;
        height: 25px;
        text-align: center;
        line-height: 50px;
        font-size: 18px;
        color: #99a2aa;
        cursor: default;

        // border: 1px solid #e1e2e5;
      }
      ::v-deep .el-tabs--left .el-tabs__item.is-left {
        text-align: center;
        width: 200px;
        height: 44px;
        font-size: 14px;
      }
    }
  }
}
</style>